package com.liang.maogouyuyin.ui.activity

import android.Manifest
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import com.liang.maogouyuyin.AppConst
import com.liang.maogouyuyin.TheBaseApplication
import com.liang.maogouyuyin.bean.AnomalyBean
import com.liang.maogouyuyin.bean.CasebookBean
import com.liang.maogouyuyin.bean.ExpenditureBean
import com.liang.maogouyuyin.bean.WeightBean
import com.liang.maogouyuyin.databinding.ActivityAddDetailBinding
import com.liang.maogouyuyin.local.LocalRepository
import com.liang.maogouyuyin.ui.adapter.PetAdapter
import com.liang.maogouyuyin.ui.viewmodel.AnomalyViewModel
import com.liang.maogouyuyin.ui.viewmodel.CasebookViewModel
import com.liang.maogouyuyin.ui.viewmodel.ExpenditureViewModel
import com.liang.maogouyuyin.ui.viewmodel.PetViewModel
import com.liang.maogouyuyin.ui.viewmodel.WeightViewModel
import com.liang.maogouyuyin.utils.DateUtil
import com.liang.maogouyuyin.utils.lzy.PermissionUtils
import com.liang.maogouyuyin.widget.popup.SelectPetPopup
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.TimePickerPopup
import java.io.File
import java.io.FileOutputStream
import java.util.Calendar
import java.util.Date

class AddDetailActivity : AppCompatActivity() {

    private lateinit var binding: ActivityAddDetailBinding

    private lateinit var petViewModel: PetViewModel
    private lateinit var expenditureViewModel: ExpenditureViewModel
    private lateinit var weightViewModel: WeightViewModel
    private lateinit var anomalyViewModel: AnomalyViewModel
    private lateinit var casebookViewModel: CasebookViewModel

    private var type = 0

    private var recordDate = -1L

    private var tempUri = ""

    private val casebookLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
        it?.also {
            if (tempUri.isNotEmpty())
                deleteImage(tempUri)
            tempUri = it.toString()
            Glide.with(this).load(it).into(binding.addDetailPaperCasebook)
        }
    }

    private val anomalyLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
        it?.also {
            if (tempUri.isNotEmpty())
                deleteImage(tempUri)
            tempUri = it.toString()
            Glide.with(this).load(it).into(binding.addDetailAnomalyImage)
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityAddDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initData()
        initView()
        initClick()
        updateUI()
    }

    override fun onDestroy() {
        AppConst.bean = null
        super.onDestroy()
    }

    private fun initData() {
        petViewModel = TheBaseApplication.getInstance().petViewModel
        expenditureViewModel = TheBaseApplication.getInstance().expenditureViewModel
        weightViewModel = TheBaseApplication.getInstance().weightViewModel
        anomalyViewModel = TheBaseApplication.getInstance().anomalyViewModel
        casebookViewModel = TheBaseApplication.getInstance().casebookViewModel
        type = intent.getIntExtra("type", 0)
    }

    private fun initView() {
        petViewModel.pet.value?.also {
            binding.addDetailTitle.text = it.name
            binding.addDetailPetName.text = it.name
            Glide.with(this).load(File(it.profile)).into(binding.addDetailProfile)
        }

        when (type) {
            0 -> {
                binding.addDetailExpenditureAnomalyLayout.visibility = View.VISIBLE
                AppConst.bean?.also {
                    val bean = it as ExpenditureBean
                    recordDate = bean.date
                    binding.addDetailDate.text = DateUtil.formatTimeStamp(recordDate)
                    binding.addDetailExpenditure.setText(bean.money.toString())
                    binding.addDetailContent.setText(bean.content)
                }
            }
            1 -> {
                binding.addDetailWeightLayout.visibility = View.VISIBLE
                binding.addDetailContentLayout.visibility = View.GONE
                AppConst.bean?.also {
                    val bean = it as WeightBean
                    recordDate = bean.date
                    binding.addDetailDate.text = DateUtil.formatTimeStamp(recordDate)
                    binding.addDetailWeight.setText(bean.weight.toString())
                }
            }
            2 -> {
                binding.addDetailExpenditureAnomalyLayout.visibility = View.VISIBLE
                binding.addDetailAnomalyText.text = "异常名称"
                binding.addDetailExpenditure.inputType = InputType.TYPE_CLASS_TEXT
                binding.addDetailAnomalyLayout.visibility = View.VISIBLE
                AppConst.bean?.also {
                    val bean = it as AnomalyBean
                    recordDate = bean.date
                    binding.addDetailDate.text = DateUtil.formatTimeStamp(recordDate)
                    binding.addDetailExpenditure.setText(bean.name)
                    binding.addDetailContent.setText(bean.content)
                    tempUri = bean.image
                    if (bean.image.isNotEmpty())
                        Glide.with(this).load(File(bean.image)).into(binding.addDetailAnomalyImage)
                }
            }
            3 -> {
                binding.addDetailHospitalLayout.visibility = View.VISIBLE
                binding.addDetailCasebookLayout.visibility = View.VISIBLE
                binding.addDetailPaperCasebookLayout.visibility = View.VISIBLE
                AppConst.bean?.also {
                    val bean = it as CasebookBean
                    recordDate = bean.date
                    binding.addDetailDate.text = DateUtil.formatTimeStamp(recordDate)
                    binding.addDetailHospital.setText(bean.hospital)
                    binding.addDetailCasebook.setText(bean.casebook)
                    tempUri = bean.image
                    if (bean.image.isNotEmpty())
                        Glide.with(this).load(File(bean.image)).into(binding.addDetailPaperCasebook)
                    binding.addDetailContent.setText(bean.content)
                }
            }
        }

        val textWatcher10 = object: TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.length == 10) {
                    Toast.makeText(this@AddDetailActivity, "最多可输入10个字", Toast.LENGTH_SHORT).show()
                }
            }

            override fun afterTextChanged(s: Editable?) {}
        }

        val textWatcher20 = object: TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.length == 20) {
                    Toast.makeText(this@AddDetailActivity, "最多可输入20个字", Toast.LENGTH_SHORT).show()
                }
            }

            override fun afterTextChanged(s: Editable?) {}
        }

        binding.addDetailWeight.addTextChangedListener(textWatcher10)
        binding.addDetailWeight.setOnClickListener {
            if (binding.addDetailWeight.text.length == 10)
                Toast.makeText(this@AddDetailActivity, "最多可输入10个字", Toast.LENGTH_SHORT).show()
        }

        binding.addDetailExpenditure.addTextChangedListener(textWatcher10)
        binding.addDetailExpenditure.setOnClickListener {
            if (binding.addDetailExpenditure.text.length == 10)
                Toast.makeText(this@AddDetailActivity, "最多可输入10个字", Toast.LENGTH_SHORT).show()
        }

        binding.addDetailContent.addTextChangedListener(textWatcher20)
        binding.addDetailContent.setOnClickListener {
            if (binding.addDetailContent.text.length == 20)
                Toast.makeText(this@AddDetailActivity, "最多可输入20个字", Toast.LENGTH_SHORT).show()
        }

        binding.addDetailCasebook.addTextChangedListener(textWatcher20)
        binding.addDetailCasebook.setOnClickListener {
            if (binding.addDetailCasebook.text.length == 20)
                Toast.makeText(this@AddDetailActivity, "最多可输入20个字", Toast.LENGTH_SHORT).show()
        }

        binding.addDetailHospital.addTextChangedListener(textWatcher20)
        binding.addDetailHospital.setOnClickListener {
            if (binding.addDetailHospital.text.length == 20)
                Toast.makeText(this@AddDetailActivity, "最多可输入20个字", Toast.LENGTH_SHORT).show()
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun initClick() {
        binding.addDetailToolBar.setNavigationOnClickListener {
            finish()
        }

        binding.addDetailTitle.setOnClickListener {
            showSelectPopup()
        }

        binding.addDetailTitleImage.setOnClickListener {
            showSelectPopup()
        }

        binding.addDetailProfilePicker.setOnClickListener {
            showSelectPopup()
        }

        binding.addDetailDatePicker.setOnClickListener {
            val calendar = Calendar.getInstance()
            XPopup.Builder(this)
                .asCustom(TimePickerPopup(this)
                    .setDefaultDate(calendar)
                    .setDateRange(null, calendar)
                    .setTimePickerListener(object: TimePickerListener{
                        override fun onTimeChanged(date: Date?) {}

                        override fun onTimeConfirm(date: Date?, view: View?) {
                            binding.addDetailDate.text = DateUtil.formatTimeStamp(date!!.time)
                            recordDate = date.time
                        }

                        override fun onCancel() {}
                    })
                ).show()
        }

        binding.addDetailPaperCasebook.setOnClickListener {
            PermissionUtils.tryToDoSomethingWithCheckPermissionAndCode(
                this,
                arrayOf(Manifest.permission.READ_MEDIA_IMAGES),
                2,
                "没有权限将无法获取图片"
            ) {
                casebookLauncher.launch("image/*")
            }
        }

        binding.addDetailAnomalyImage.setOnClickListener {
            PermissionUtils.tryToDoSomethingWithCheckPermissionAndCode(
                this,
                arrayOf(Manifest.permission.READ_MEDIA_IMAGES),
                2,
                "没有权限将无法获取图片"
            ) {
                anomalyLauncher.launch("image/*")
            }
        }

        binding.addDetailDelete.setOnClickListener {
            AppConst.bean?.also {
                when(type) {
                    0 -> expenditureViewModel.deleteExpenditure(it as ExpenditureBean)
                    1 -> weightViewModel.deleteWeight(it as WeightBean)
                    2 -> {
                        val bean = it as AnomalyBean
                        if (bean.image.isNotEmpty())
                            deleteImage(bean.image)
                        anomalyViewModel.deleteAnomaly(bean)
                    }
                    3 -> {
                        val bean = it as CasebookBean
                        if (bean.image.isNotEmpty())
                            deleteImage(bean.image)
                        casebookViewModel.deleteCasebook(bean)
                    }
                }
            }
            finish()
        }

        binding.addDetailSave.setOnClickListener {
            if (recordDate == -1L) {
                Toast.makeText(this, "请选择日期", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            when (type) {
                0 -> {
                    if (binding.addDetailExpenditure.text.isEmpty()) {
                        Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show()
                        return@setOnClickListener
                    }
                    if (AppConst.bean != null) {
                        val bean = AppConst.bean as ExpenditureBean
                        bean.name = LocalRepository.currentPet
                        bean.money = binding.addDetailExpenditure.text.toString().toFloat()
                        bean.content = binding.addDetailContent.text.toString()
                        bean.date = recordDate
                        expenditureViewModel.updateExpenditure(bean)
                    } else
                        expenditureViewModel.saveExpenditure(LocalRepository.currentPet, binding.addDetailExpenditure.text.toString().toFloat(), binding.addDetailContent.text.toString(), recordDate)
                }
                1 -> {
                    if (binding.addDetailWeight.text.isEmpty()) {
                        Toast.makeText(this, "请输入体重", Toast.LENGTH_SHORT).show()
                        return@setOnClickListener
                    }
                    if (AppConst.bean != null) {
                        val bean = AppConst.bean as WeightBean
                        bean.name = LocalRepository.currentPet
                        bean.weight = binding.addDetailWeight.text.toString().toFloat()
                        bean.date = recordDate
                        weightViewModel.updateWeight(bean)
                    } else
                        weightViewModel.saveWeight(LocalRepository.currentPet, binding.addDetailWeight.text.toString().toFloat(), recordDate)
                }
                2 -> {
                    if (binding.addDetailExpenditure.text.isEmpty()) {
                        Toast.makeText(this, "请输入异常名称", Toast.LENGTH_SHORT).show()
                        return@setOnClickListener
                    }
                    if (AppConst.bean != null) {
                        val bean = AppConst.bean as AnomalyBean
                        bean.name = LocalRepository.currentPet
                        bean.anomalyName = binding.addDetailExpenditure.text.toString()
                        bean.date = recordDate
                        bean.content = binding.addDetailContent.text.toString()
                        if (!tempUri.contentEquals(bean.image)) {
                            deleteImage(bean.image)
                            bean.image = saveImage()
                        }
                        anomalyViewModel.updateAnomaly(bean)
                    } else
                        anomalyViewModel.saveAnomaly(LocalRepository.currentPet, binding.addDetailExpenditure.text.toString(), recordDate, binding.addDetailContent.text.toString(), saveImage())
                }
                3 -> {
                    if (binding.addDetailHospital.text.isEmpty()) {
                        Toast.makeText(this, "请输入就诊医院", Toast.LENGTH_SHORT).show()
                        return@setOnClickListener
                    } else if (binding.addDetailCasebook.text.isEmpty()) {
                        Toast.makeText(this, "请输入病症", Toast.LENGTH_SHORT).show()
                        return@setOnClickListener
                    }
                    if (AppConst.bean != null) {
                        val bean = AppConst.bean as CasebookBean
                        bean.name = LocalRepository.currentPet
                        bean.date = recordDate
                        bean.hospital = binding.addDetailHospital.text.toString()
                        bean.casebook = binding.addDetailCasebook.text.toString()
                        bean.content = binding.addDetailContent.text.toString()
                        if (!tempUri.contentEquals(bean.image)) {
                            deleteImage(bean.image)
                            bean.image = saveImage()
                        }
                        casebookViewModel.updateCasebook(bean)
                    } else
                        casebookViewModel.saveCasebook(LocalRepository.currentPet, recordDate, binding.addDetailHospital.text.toString(), binding.addDetailCasebook.text.toString(), binding.addDetailContent.text.toString(), saveImage())
                }
            }

            finish()
        }
    }

    private fun updateUI() {
        petViewModel.pet.observe(this) {
            Glide.with(this).load(File(it.profile)).into(binding.addDetailProfile)
        }
    }

    private fun showSelectPopup() {
        XPopup.Builder(this)
            .asCustom(SelectPetPopup(this)
                .setList(petViewModel.petList.value!!)
                .setListener(object: PetAdapter.SelectListener{
                    override fun select(petName: String) {
                        binding.addDetailTitle.text = petName
                        binding.addDetailPetName.text = petName
                        petViewModel.loadPetByName(petName)
                    }
                })
            ).show()
    }

    private fun saveImage(): String {
        if (tempUri.isEmpty())
            return tempUri
        val inputStream = contentResolver.openInputStream(Uri.parse(tempUri))

        val file = File(filesDir, tempUri.hashCode().toString())
        FileOutputStream(file).use {
                outputStream -> inputStream?.copyTo(outputStream)
        }

        inputStream?.close()
        return file.absolutePath
    }

    private fun deleteImage(url: String) {
        val file = File(url)
        if(file.exists())
            file.delete()
    }
}